package com.tuzhi.sys.web.controller;

import com.alibaba.fastjson2.JSONObject;
import com.tuzhi.base.service.BaseService;
import com.tuzhi.base.web.controller.SimpleBaseController;
import com.tuzhi.base.web.helper.AjaxResultHelper;
import com.tuzhi.base.web.vo.AjaxResultVO;
import com.tuzhi.common.constants.ResultConstant;
import com.tuzhi.common.domain.LoginUserBO;
import com.tuzhi.common.domain.ResultBO;
import com.tuzhi.common.exception.BusinessException;
import com.tuzhi.common.helper.ResultHelper;

import com.tuzhi.security.service.impl.TokenServiceImpl;
import com.tuzhi.sys.jpa.entity.SysUserEntity;
import com.tuzhi.sys.jpa.entity.SysUserPersonalEntity;
import com.tuzhi.sys.service.SysUserPersonalService;
import com.tuzhi.util.StringTzUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/sys/user/personal")
@Slf4j
public class SysUserPersonalController extends SimpleBaseController<Long, SysUserPersonalEntity, Object> {

    @Autowired
    SysUserPersonalService sysUserPersonalService;

    @Autowired
    TokenServiceImpl tokenService;

    @Override
    protected BaseService getThisService() {
        return sysUserPersonalService;
    }

    @PostMapping({"/saveConfig"})
    public AjaxResultVO saveConfig(@RequestBody String configStr) {
        if (StringTzUtil.isBlankNull(configStr)) {
            log.warn("传入参数为空!");
            throw new BusinessException("传入参数为空!");
        }
        log.info(configStr);
        LoginUserBO loginUserBO = tokenService.getCurUser();
        if (loginUserBO == null) {
            throw new BusinessException("获取用户身份失败,可能token 过期");
        }
        SysUserPersonalEntity entity = new SysUserPersonalEntity();
        entity.setUserId(loginUserBO.getUserId());
        entity.setConfig(configStr);
        sysUserPersonalService.save(entity);
        return AjaxResultHelper.success();
    }

    @GetMapping({"/getConfig"})
    public AjaxResultVO getConfig() {
        LoginUserBO loginUserBO = tokenService.getCurUser();
        if (loginUserBO == null) {
            throw new BusinessException("获取用户身份失败,可能token 过期");
        }
        SysUserPersonalEntity entity = sysUserPersonalService.get(loginUserBO.getUserId());
        AjaxResultVO ajaxResultVO = AjaxResultHelper.success();
        if (entity != null) {
            ajaxResultVO.setData(entity.getConfig());
        } else {
            ajaxResultVO.setData("{}");
        }
        return ajaxResultVO;
    }

}
